#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/11/1 15:55
# @Description: 对每个仓库进行手动刷新修改
# @Author  : Tom_zc
# @FileName: ci_config.py
# @Software: PyCharm
from dataclasses import dataclass

import yaml
import click
import logging
import os
import sys
import time

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(BASE_DIR, "ci-scripts"))

LOG_FORMAT = "%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
from auto_config import WorkFlow

_yaml_config_path = "./refresh_config.yaml"


def _load_yaml(file_path):
    with open(file_path, encoding="utf-8") as fp:
        content = yaml.load(fp.read(), Loader=yaml.Loader)
    return content


def _load_from_yaml():
    config = _load_yaml(_yaml_config_path)
    env_class = {
        "ak": config["ak"],
        "sk": config["sk"],
        # "obs_endpoint": config["obs_endpoint"],
        # "obs_static_endpoint": config["obs_static_endpoint"],
        # "obs_bucket_name": config["obs_bucket_name"],
        "gitcode_domain": config["gitcode_domain"],
        "gitcode_api_domain": config["gitcode_api_domain"],
        "gitcode_username": config["gitcode_username"],
        "gitcode_rw_token": config["gitcode_rw_token"],
        "gitcode_token": config["gitcode_r_token"],
        # "conan_user": config["conan_r_user"],
        # "conan_password": config["conan_r_password"],
        "project_id": config["project_id"],
        # "sca_appId": config["sca_appId"],
        # "sca_secretKey": config["sca_secretKey"],
        # "sca_domain": config["sca_domain"],
        "image_version": config["image_version"],
        "variable_id": config["variable_id"]
    }
    if config.get("repo"):
        repos_lists = config["repo"]
    else:
        repos_dir = os.path.join(BASE_DIR, "ci-repos")
        repos_lists = [dir_name for dir_name in os.listdir(repos_dir) if not dir_name.startswith(".")]
    return env_class, repos_lists, config


def _load_from_env(repo):
    env_class = {
        "ak": os.getenv("ak"),
        "sk": os.getenv("sk"),
        "obs_endpoint": os.getenv("obs_endpoint"),
        "obs_static_endpoint": os.getenv("obs_static_endpoint"),
        "obs_bucket_name": os.getenv("obs_bucket_name"),
        "gitcode_domain": os.getenv("gitcode_domain"),
        "gitcode_api_domain": os.getenv("gitcode_api_domain"),
        "gitcode_username": os.getenv("gitcode_username"),
        "gitcode_rw_token": os.getenv("gitcode_rw_token"),
        "gitcode_token": os.getenv("gitcode_r_token"),
        "conan_user": os.getenv("conan_r_user"),
        "conan_password": os.getenv("conan_r_password"),
        "project_id": os.getenv("PROJECT_ID"),
        "sca_appId": os.getenv("sca_appId"),
        "sca_secretKey": os.getenv("sca_secretKey"),
        "sca_domain": os.getenv("sca_domain"),
        "image_version": os.getenv("image_version"),
        "variable_id": os.getenv("variable_id")
    }
    if repo:
        repos_lists = [repo]
    else:
        repos_dir = os.path.join(BASE_DIR, "ci-repos")
        repos_lists = [dir_name for dir_name in os.listdir(repos_dir) if not dir_name.startswith(".")]
    return env_class, repos_lists


# 读取refresh_config.yaml配置文件，如果里面指定仓库，则对对应的仓库进行修改，否则修改所有的仓库
@click.command()
@click.option("--enable_from_yaml", default=True, help='The choice of read config from yaml or env')
@click.option("--repo", default="", help='The repo of ci')
def main(enable_from_yaml, repo):
    logging.info("-" * 24 + "start to read config from CodeArts pipeline" + "-" * 24)
    config = None
    if enable_from_yaml:
        env_class, repos_lists, config = _load_from_yaml()
    else:
        env_class, repos_lists = _load_from_env(repo)
    # 1.从ci-repos获取下面的仓库信息
    # set the env class
    failed_repos = list()
    for ci_repo in repos_lists:
        try:
            logging.info("start to handler:{}".format(ci_repo))
            workflow = WorkFlow(env_class, "ascend-archive", ci_repo, "")
            workflow.update(config.get("force"))
        except Exception as e:
            logging.exception("auto_config:{}".format(str(e)))
            failed_repos.append(ci_repo)
        # time.sleep(31)
    if failed_repos:
        logging.info("find failed repo: {}".format(",".join(failed_repos)))
    logging.info("-" * 24 + "end to auto config ci" + "-" * 24)


if __name__ == '__main__':
    main()
